/*
 * @Author: lvye
 * @Description:
 * @Date: 2023-07-12 11:12:59
 * @LastEditTime: 2023-08-21 11:28:10
 * @FilePath: \vue3-ts\src\store\login\login.ts
 */
import { Module } from "vuex"
import {
  accountLoginRequest,
  requestUserInfoById
  // requestUserMenusByRoleId
} from "@/service/login/login"
import { menuData } from "@/mock/menu"
import { IloginState } from "./type"
import { IRootState } from "../type"
import { IAccount } from "@/service/login/type"
import localCache from "@/utils/cache"
import router from "@/router"
import { mapMenusToRoutes } from "@/utils/map-menu"

const loginModule: Module<IloginState, IRootState> = {
  namespaced: true,
  state() {
    return {
      token: "",
      userInfo: "",
      userMenus: []
    }
  },
  mutations: {
    changeToken(state, token: string) {
      state.token = token
    },
    changeUserInfo(state, userInfo: any) {
      state.userInfo = userInfo
    },
    changeUserMenus(state, userMenus: any) {
      state.userMenus = userMenus
      // 注册动态路由
      // userMenus => routes  菜单和路由映射
      const routes = mapMenusToRoutes(userMenus)
      console.log(routes, "routesroutesroutes")
      // 将routes => router.main.children
      routes.forEach((route) => {
        router.addRoute("main", route)
      })
    }
  },
  getters: {},
  actions: {
    async accountLoginAction({ commit, dispatch }, payload: IAccount) {
      const loginResult = await accountLoginRequest(payload)
      console.log(loginResult, "loginResult")
      const { uuid, token } = loginResult.data
      commit("changeToken", token)
      localCache.setCache("token", token)
      // 发送初始化的请求(完整的role/department)
      dispatch("getInitialDataAction", null, { root: true })
      // 请求用户信息
      const userInfo = await requestUserInfoById(uuid)
      console.log(userInfo.data, "userInfo")
      const { info } = userInfo.data
      commit("changeUserInfo", info)
      localCache.setCache("userInfo", info)
      // 请求用户菜单
      // const userMenusResult = await requestUserMenusByRoleId(info.uuid)
      // const userMenus = userMenusResult.data
      // 接口不通，用mock数据
      const userMenus = menuData
      commit("changeUserMenus", userMenus)
      localCache.setCache("userMenus", userMenus)

      // 4.跳到首页
      router.push("/main")
    },
    loadLocalLogin({ commit, dispatch }) {
      // 防止刷新页面vuex丢失
      const token = localCache.getCache("token")
      if (token) {
        commit("changeToken", token)
        dispatch("getInitialDataAction", null, { root: true })
      }
      const userInfo = localCache.getCache("userInfo")
      if (userInfo) {
        commit("changeUserInfo", userInfo)
      }
      const userMenus = localCache.getCache("userMenus")
      if (userMenus) {
        commit("changeUserMenus", userMenus)
      }
    }
  }
}
export default loginModule
